'use strict'
import Storage from '@/utils/storage'
import { asyncDevice } from './systeminfo'
import request from '@/utils/request'
import Utils from '@/utils'
import Modules from '@/api'

// 为了解决setItemEvent不立即生效，使用事件派发强制更高
Storage.dispatchLocalStorageEvent()
Storage.dispatchSessionStorageEvent()

// 全局设备注册授权
const systemInfo = Storage.get('systemInfo')
if (!systemInfo) {
  asyncDevice().then(res => {
    Storage.set('systemInfo', res)
  })
}

// window全局监听localStorage的setItem事件以及时更新
window.addEventListener('setSessionItemEvent', function(e) {
  console.log('// ---- Set SessionItem Event:', e.newValue)
})
window.addEventListener('setLocalItemEvent', function(e) {
  console.log('// ---- Set LocalItem Event:', e.newValue)
})

const install = Vue => {
  if (install.installed) return
  install.installed = true
  Object.defineProperties(Vue.prototype, {
    $storage: {
      get() {
        return Storage
      }
    },
    axios: {
      get() {
        return request
      }
    },
    $http: {
      get() {
        return Modules
      }
    },
    $utils: {
      get() {
        return Utils
      }
    }
  })
}

export default install
